import {
	usersStore
} from 'store/users.js';
import config from "@/config.js"
class request {
	#state = {
		'200': (data) => data.result,
		'201': (data) => console.warn(data),
		'400': (data) => console.warn('请求失败！请您稍后重试', data),
		'401': (data) => this.#tokenExpiration(data),
		'403': (data) => console.warn('当前账号无权限访问！', data),
		'404': (data) => console.warn('你所访问的资源不存在！', data),
		'405': (data) => console.warn('请求方式错误！请您稍后重试！', data),
		'408': (data) => console.warn('请求超时！请您稍后重试！', data),
		'500': (data) => data,
		'502': (data) => console.warn('网关错误！', data),
		'503': (data) => console.warn('服务不可用！', data),
		'504': (data) => console.warn('网关超时！', data)
	}
	constructor(baseURL) {
		this.baseURL = baseURL || config.interface;
		this.usersStore = usersStore()
		this.requestList = {}
	}
	#tokenExpiration(data) {
		this.usersStore.removeUsers()
		uni.showToast({
			title: data.message || '登录失效！请您重新登录',
			icon: "exception",
			duration: 2000
		})
		uni.redirectTo({
			url: '/pages/index/index'
		})
	}
	get(url, data) {
		return this.#request({
			url,
			method: 'GET',
			data
		});
	}
	post(url, data) {
		return this.#request({
			url,
			method: 'POST',
			data
		});
	}
	put(url, data) {
		return this.#request({
			url,
			method: 'PUT',
			data
		});
	}
	delete(url, data) {
	const queryParams = Object.keys(data)
	  .map(key => `${key}=${data[key]}`)
	  .join('&');
		return this.#request({
			url: url + '?' + queryParams,
			method: 'DELETE',
		});
	}
	#request(options) {
		return this.#beforeRequest(options).then(opt => {
			if(this.requestList[options.url])return
			return uni.request({
				...opt
			})
		}).then(res => {
			delete this.requestList[options.url]
			Object.keys(this.requestList).length || uni.hideLoading();
			return this.#handleResponse(res.data)
		}, () => {
			uni.hideLoading()
			this.requestList[options.url] = {}
			uni.showToast({
				title: '无法连接服务',
				icon: "error",
				duration: 2000
			})
		})
	}
	#beforeRequest(options) {
		return new Promise(resolve => {
			options.url = this.baseURL + options.url;
			this.requestList[options.url] = null
			uni.showLoading({
				title: '加载中'
			});
			options.method = options.method || 'GET';
			const token = this.usersStore.users.token || ''
			token && (options.header = {
				token
			})
			resolve(options)
		})
	}
	#handleResponse(data) {
		return new Promise((resolve, reject) => this.#state[data.code] ? resolve(this.#state[data.code](data)) :
			reject(data))
	}
}
export default request